package com.example.demo.oo.service;

import com.example.demo.app.Exception;
import com.example.demo.app.sms.Sms;
import com.example.demo.oo.domain.Captcha;
import com.example.demo.oo.repository.CaptchaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CaptchaService {

    @Autowired
    CaptchaRepository repository;

    @Autowired
    Sms sms;

    public void send(Captcha captcha) {

        // 如何区分业务流程、业务逻辑

        // 生成验证码信息
        captcha.generate();
        // 发送短信
        sendSMS(captcha);
        // 存储
        save(captcha);

    }

    public void check(Captcha captcha) {

        // 验证
        valid(captcha);
        // 验证码失效
        delete(captcha);
    }

    private void valid(Captcha captcha) {

        Captcha cache = of(captcha);
        if (cache == null) {
            throw new Exception("验证码已过期");
        }

        if (!captcha.getValue().equals(cache.getValue())) {
            throw new Exception("验证码错误");
        }
    }

    private void sendSMS(Captcha captcha) {
        sms.send(captcha.getMobile().getValue(), captcha.getContent());
    }

    protected Captcha of(Captcha captcha) {
        return repository.find(captcha);
    }

    protected void save(Captcha captcha) {
        repository.save(captcha);
    }

    protected void delete(Captcha captcha) {
        repository.delete(captcha);
    }

}
